<?php

defined('_SECURITY_TOKEN') or die("caia fora");

abstract class framework {
	
	protected static $_values = array();
	
	private static $public_key="";
	private static $hash_hmac="";
	private static $user_id=0;
	
	public function __construct(){


		


	}
	
	public static function setAttribute( $varName, $val ){ 
    	self::$_values[ $varName ] = $val; 
	}
	
	public static function getAttribute( $varName ){ 

		try {
        	
			if( !isset( self::$_values[ $varName ] ))
	        	throw new AppException( ATTRIBUTE_NOT_DEFINED.': '.$varName );
	   					
	    }
	    catch (AppException $e) {
	    	throw new AppException( $e->getMessage() );
	        //echo "#1Caught TestException ('{$e->getMessage()}')\n{$e}\n";
	    }
	    //catch (Exception $e) {
	    //    echo "#Erro Fatal ('{$e->getMessage()}')\n{$e}\n";
	   // }
		
		
	    return self::$_values[ $varName ]; 
	}

	
	public static function getSeparator(){
		return _SEPARATOR_SO;
	}
	
	public static function require_file( $filename=""){
		

	}
	
	
	public static function instanceLibrary( $lib_path, $lib_name, $package='' ){
		
		$result	=	false;
		
		try {
			
			if(empty($package)){
				
				$filename	=	PATH_FRAMEWORK_LIBRARY
							._SEPARATOR_SO
							.$lib_path
							._SEPARATOR_SO
							.$lib_name
							.'.class.php';
							
			}else{
				
				$filename	=	PATH_FRAMEWORK_LIBRARY
							._SEPARATOR_SO
							.$package
							._SEPARATOR_SO
							.$lib_path
							._SEPARATOR_SO
							.$lib_name
							.'.class.php';
							
			}
			
									
			if( file_exists( $filename ) )								
				require_once( $filename );
			else
				throw new AppException( FILE_NOT_FOUND.': '.$filename );
			
			$result=	new $lib_name();
					
	    }
	    catch (AppException $e) {
	    	throw new AppException( $e->getMessage() );

	    }

		
		return $result;
				
		
	}


	
	public static function getDb( $dbtype="mysql" ){
		
		$result	=	false;
		
		try {
			
			$filename	=	PATH_FRAMEWORK_LIBRARY
							._SEPARATOR_SO
							."bm"
							._SEPARATOR_SO
							.'db'
							._SEPARATOR_SO
							.$dbtype//'mysql'
							._SEPARATOR_SO
							.$dbtype//'mysql'
							.'.class.php';
									
			if( file_exists( $filename ) )								
				require_once( $filename );
			else
				throw new AppException( FILE_NOT_FOUND.': '.$filename );
			
			$db_host	=	configuration::db_server;
			$db_user	=	configuration::db_username;
			$db_pass	=	configuration::db_password;
			$db_name	=	configuration::db_name;
			//$tb_session	=	configuration::$table_session;
			
			
			$result	=	new $dbtype($db_host,
									$db_user,
									$db_pass,
									$db_name);
					
	    }
	    catch (AppException $e) {
	    	throw new AppException( $e->getMessage() );
	        //echo "#1Caught TestException ('{$e->getMessage()}')\n{$e}\n";
	    }
	   // catch (Exception $e) {
	    //    echo "#Erro Fatal ('{$e->getMessage()}')\n{$e}\n";
	    //}
		
		
		return $result;
				
		
	}
	
	
	
	public static function session_logout(){
		
		//session_destroy();
		
		$result=false;
		
		try{
				 		
			$db = application::getDb( configuration::db_type );
	// 		
			$db->setParameters(configuration::db_server, 
								configuration::db_port, 
								configuration::db_username, 
								configuration::db_password,
								configuration::db_name);
	
			$query = sprintf("UPDATE \"%s%s\" SET public_key=''"
							."WHERE public_key='%s';",
							configuration::table_prefix,
							configuration::table_user, 
							self::getHeaderPublicKey());
		
			try{	
				$result = $db->setQuery($query);
				
			}catch (AppException $e) {
    			$result=false;
			}
		
		}
	    catch (AppException $e) {
	    	throw new AppException( $e->getMessage() );
	    }
		

	}
	
	
	public static function getHeaderHMAC(){
		
		foreach (getallheaders() as $name => $value) 
			if($name == 'X-Hash'){
				self::$hash_hmac = $value;
				break;
			}
		
		return self::$hash_hmac;
	}
	
	
	public static function getHeaderPublicKey(){
		
		foreach (getallheaders() as $name => $value)		
			if($name == 'X-Public'){				
				self::$public_key = $value;
				break;
			}
		
		return self::$public_key;
	}
	
	
	
	public static function convertPublicKeyToUsername($public_key){
		
		$result=false;
		
		try{
				 		
			$db = application::getDb( configuration::db_type );
	// 		
			$db->setParameters(configuration::db_server, 
								configuration::db_port, 
								configuration::db_username, 
								configuration::db_password,
								configuration::db_name);
	
			if( !empty($public_key)){
						
				$query = sprintf("SELECT email FROM \"%s%s\" 
								WHERE public_key='%s';",
						configuration::table_prefix,
	                 	configuration::table_user, 
	                 	$public_key);
						
				$result = $db->getQuery($query);
				
				if($result)
					$result = $result[0]->email;
			}
		
		}
	    catch (AppException $e) {
	    	throw new AppException( $e->getMessage() );
	    }
		

		return $result;

		
	}


	
	
	public static function convertPublicKeyToId($public_key){
		
		$result=false;
		
		try{
				 		
			$db = application::getDb( configuration::db_type );
	// 		
			$db->setParameters(configuration::db_server, 
								configuration::db_port, 
								configuration::db_username, 
								configuration::db_password,
								configuration::db_name);
	
			if( !empty($public_key)){
						
				$query = sprintf("SELECT id FROM \"%s%s\" 
								WHERE public_key='%s';",
						configuration::table_prefix,
	                 	configuration::table_user, 
	                 	$public_key);
						//exit("dddd=".$query);
				$result = $db->getQuery($query);
				
				if($result)
					$result = $result[0]->id;
			}
		
		}
	    catch (AppException $e) {
	    	throw new AppException( $e->getMessage() );
	    }
		

		return $result;

		
	}


	public static function convertPublicKeyToPrivateKey($public_key){
		
		$result=false;
		
		try{
				 		
			$db = application::getDb( configuration::db_type );
	// 		
			$db->setParameters(configuration::db_server, 
								configuration::db_port, 
								configuration::db_username, 
								configuration::db_password,
								configuration::db_name);
	
			if( !empty($public_key)){
						
				$query = sprintf("SELECT private_key FROM \"%s%s\" 
								WHERE public_key='%s';",
						configuration::table_prefix,
	                 	configuration::table_user, 
	                 	$public_key);
						
				$result = $db->getQuery($query);
				
				if($result)
					$result = $result[0]->private_key;
			}
		
		}
	    catch (AppException $e) {
	    	throw new AppException( $e->getMessage() );
	    }
		

		return $result;

		
	}
	
	
	
	public static function check_authentication(){
		
		$xpublic=self::getHeaderPublicKey();
		$xhash=self::getHeaderHMAC();

		/*foreach (getallheaders() as $name => $value) {
		
			if($name == 'X-Public')
				$xpublic = $value;

			if($name == 'X-Hash')
				$xhash = $value;


		}
		*/
		$private_key 	=	self::convertPublicKeyToPrivateKey($xpublic);
		
		//exit($xpublic);
		
		if( $private_key ){
			
			self::$public_key=$xpublic;
		
			//$parameters =  (empty($_REQUEST['parameters'])?'':$_REQUEST['parameters']);
		
			$parameters	=	application::getMessageHMAC();
			
			$hash_hmac	=	hash_hmac('md5', $parameters, $private_key);
	
			//echo $parameters;
	
	
	
		//echo "hash_hmac".$hash_hmac." - ".$xhash;
	
		//exit("fim");
	
			if( $hash_hmac == $xhash){
				//esta autorizado a continuar
				
			}else{
				
				self::session_logout();
				
				//não tem acesso
				$result=array("status"=>0,
										"data"=>MSG_25_LOGINI_EXIGIDO,
										"notification"=>25);
										
				echo json_encode($result); 					
				exit();
			}
			
		}else{
			
			$result=array("status"=>0,
										"data"=>MSG_25_LOGINI_EXIGIDO,
										"notification"=>25);
										
				echo json_encode($result); 					
				exit();
				
		}
		
		
		//exit("private key ".$hash_hmac. "=".$xhash	 );

	}
	
	
	public static function IsAuthenticationRequired( $required=FALSE, $redirect="" ){
		
		if( $required == TRUE){
			
			self::check_authentication();
			
			if( !self::getAuthentication() ){
				
				//$result	=	array("status"=>"restrict access");
				
				$result=array("status"=>0,
									"data"=>MSG_25_LOGINI_EXIGIDO,
									"notification"=>25);
									
				echo json_encode($result); 					
				exit();
			
			}
		}
				
	}
	
	
	public static function getAuthentication(){
		
		$public_key = self::getHeaderPublicKey();
		
		if(!empty($public_key)){
			
			$id =	self::convertPublicKeyToId(
								self::getHeaderPublicKey()
								);
		}else{
			$id=false;
		}
		
		
		
		if( $id )
			return true;
		else
			return false;
		
		//return (empty($_SESSION['user_id'])? FALSE:TRUE);

	}
	
	
	public static function getAuthenticationUserName(){
		
		
		$username =	self::convertPublicKeyToUsername(
								self::getHeaderPublicKey());

		if( $username )
			return $username;
		else
			return 0;
		
		//return (empty($_SESSION['username'])? "":$_SESSION['username']);
	}
	
	
	public static function getUser_id(){
		
		if(empty(self::$user_id)){
				
			$id =	self::convertPublicKeyToId(
								self::getHeaderPublicKey()
								);
			
		}else{
			
			$id = self::$user_id;
			
		}
		
		
		
		if( $id )
			return $id;
		else
			return 0;
		
		//return (empty($_SESSION['user_id'])? 0:$_SESSION['user_id']);
		
	}
	
	
	
	
	public static function start_session( $typesession="" ){	
	
		try {
        	

			switch( $typesession ){
				
				
				case 'db':
					
					
					$filename	=	PATH_FRAMEWORK_LIBRARY
									._SEPARATOR_SO
									."bm"
									._SEPARATOR_SO
									.'session'
									._SEPARATOR_SO
									.'db'
									._SEPARATOR_SO
									.'session'
									.'.class.php';
											
					if( file_exists( $filename ) )								
						require_once( $filename );
					else
						throw new AppException( FILE_NOT_FOUND.': '
												.$filename );
			
					$db_host	=	configuration::db_server;
					$db_user	=	configuration::db_username;
					$db_pass	=	configuration::db_password;
					$db_name	=	configuration::db_name;
					$tb_session	=	configuration::table_session;
					
					$session = new session( $db_host, $db_user, 
											$db_pass, $db_name,
											$tb_session ); 
			
					session_set_save_handler(array(&$session,"open"), 
					                         array(&$session,"close"), 
					                         array(&$session,"read"), 
					                         array(&$session,"write"), 
					                         array(&$session,"destroy"), 
					                         array(&$session,"gc")); 
					break;
				case 'file':
					
					
					break;
				default:
					
					
			}
			
						
			session_start();
			
	    }
	    catch (AppException $e) {
	    	throw new AppException( $e->getMessage() );
	        //echo "#1Caught TestException ('{$e->getMessage()}')\n{$e}\n";
	    }
	   // catch (Exception $e) {
	   //     echo "#Erro Fatal ('{$e->getMessage()}')\n{$e}\n";
	   // }
		
			
		
	}


	public static function getTypeData($data){
			
		$result="";
		
		if( is_numeric($data) ){
			$result = "numeric";
		}else if(is_string($data) ){
			$result = "string";
		}
			
		return $result;
				
	}
	
	public static function convertValueToCsv($data){
			
		$result="";
		
		$type = application::getTypeData($data);
		
		switch( $type ){
			case 'numeric':{
				
				$result = $data;
			}break;
			case 'string':{
				
				$result = "\"".application::replace_ilegal($data)."\"";
				
			}break;
			default:
				
				break;
		}
			
		return $result;
				
	}
	
	
	public static function replace_ilegal($data){
			
		$result="";
		
		$result =	str_replace("\n", "", $data);
		//$result =	str_replace(" ", "", $result);
		$result =	str_replace("\"", "", $result);
			
		return $result;
				
	}
	
	public static function arrayToJson($data){
			
		return json_encode($data);
				
	}

	
	public static function arrayToCsv($data){
	
		$result="";
		$columns="";
		
		foreach( $data  as $key=>$item ){
			
			if( empty($result)){
				
				foreach( $item as $key2=>$item2 ){
					
					if( empty( $result )){
						$columns .= $key2;
						$result .= application::convertValueToCsv($item2);
						
					}else{
						$columns .= ",".$key2;
						$result .=",".application::convertValueToCsv($item2);	
					}
						
					
				}
				
			}else{
				$startline=0;
				
				foreach( $item as $key2=>$item2 ){
					
					if( empty( $startline )){
						$result .="\n";
						$result .= application::convertValueToCsv($item2);
						$startline=1;	
					}else{
						$result .=",".application::convertValueToCsv($item2);	
					}
					
				}
			}
			
			
			
		}		
			
		return $columns."\n".$result;
				
	}
	
	
	public static function arrayToSql($data){
	
		$result="";
		$columns="";
		$values="";
		
		foreach( $data  as $key=>$item ){
			
			if( empty($result)){
				
				foreach( $item as $key2=>$item2 ){
					
					if( empty( $columns )){
						$columns .= $key2;
						$values .= application::convertValueToCsv($item2);
						
					}else{
						$columns .= ",".$key2;
						$values .=",".application::convertValueToCsv($item2);	
					}
						
					
				}
				
				//$result .= "insert into table_x (".$columns.") values (".$values.")\n";
				
			}else{
				$startline=0;
				$values="";
				
				foreach( $item as $key2=>$item2 ){
					
					if( empty( $startline )){
						//$result .="\n";
						$values .= application::convertValueToCsv($item2);
						$startline=1;	
					}else{
						$values .=",".application::convertValueToCsv($item2);	
					}
					
				}
				
				//$result .= "insert into table_x (".$columns.") values (".$values.")\n";
			}
			
			$result .= "insert into table_x (".$columns.") values (".$values.");\n";
			
		}		
			
		return $result;
				
	}


	
}

?>